<?php
/**
 * 食谱控制器
 * 处理食谱推荐、定制、查询等
 */

class RecipeController {
    private $db;
    
    public function __construct() {
        $database = Database::getInstance();
        $this->db = $database->getConnection();
    }
    
    /**
     * 获取个性化食谱推荐
     */
    public function getRecommendation($data) {
        try {
            $userId = $this->getUserIdFromToken($data['token']);
            
            // 获取用户健康信息
            $healthInfo = $this->getUserHealthInfo($userId);
            
            // 根据健康信息推荐食谱
            $recommendations = $this->generateRecommendations($healthInfo);
            
            return apiSuccess($recommendations);
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
    
    /**
     * 获取每日食谱
     */
    public function getDailyRecipe($data) {
        try {
            $userId = $this->getUserIdFromToken($data['token']);
            $date = isset($data['date']) ? $data['date'] : date('Y-m-d');
            
            // 检查是否有当天的定制食谱
            $stmt = $this->db->prepare("SELECT * FROM user_recipes WHERE user_id = ? AND date = ?");
            $stmt->execute([$userId, $date]);
            $customRecipe = $stmt->fetch();
            
            if ($customRecipe) {
                // 返回定制食谱
                return apiSuccess($this->formatRecipe($customRecipe));
            }
            
            // 获取用户健康信息
            $healthInfo = $this->getUserHealthInfo($userId);
            
            // 生成推荐食谱
            $recommendations = $this->generateDailyRecommendations($healthInfo, $date);
            
            return apiSuccess($recommendations);
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
    
    /**
     * 获取食谱详情
     */
    public function getRecipeDetail($data) {
        try {
            validateParams($data, ['id']);
            
            $stmt = $this->db->prepare("SELECT r.* FROM recipes r WHERE r.id = ? AND r.status = 1");
            $stmt->execute([$data['id']]);
            $recipe = $stmt->fetch();
            
            if (!$recipe) {
                return apiError('食谱不存在');
            }
            
            // 获取食材列表
            $ingredientsStmt = $this->db->prepare("SELECT ri.*, f.name as food_name, f.image as food_image FROM recipe_ingredients ri LEFT JOIN foods f ON ri.food_id = f.id WHERE ri.recipe_id = ?");
            $ingredientsStmt->execute([$data['id']]);
            $ingredients = $ingredientsStmt->fetchAll();
            
            // 获取步骤
            $stepsStmt = $this->db->prepare("SELECT * FROM recipe_steps WHERE recipe_id = ? ORDER BY step_number ASC");
            $stepsStmt->execute([$data['id']]);
            $steps = $stepsStmt->fetchAll();
            
            $recipeDetail = [
                'id' => $recipe['id'],
                'name' => $recipe['name'],
                'image' => $recipe['image'],
                'description' => $recipe['description'],
                'cookingTime' => $recipe['cooking_time'],
                'difficulty' => $recipe['difficulty'],
                'calories' => $recipe['calories'],
                'protein' => $recipe['protein'],
                'carbohydrate' => $recipe['carbohydrate'],
                'fat' => $recipe['fat'],
                'sugar' => $recipe['sugar'],
                'purine' => $recipe['purine'],
                'suitableFor' => json_decode($recipe['suitable_for'], true) ?: [],
                'ingredients' => array_map(function($ingredient) {
                    return [
                        'foodId' => $ingredient['food_id'],
                        'foodName' => $ingredient['food_name'],
                        'foodImage' => $ingredient['food_image'],
                        'quantity' => $ingredient['quantity'],
                        'unit' => $ingredient['unit']
                    ];
                }, $ingredients),
                'steps' => array_map(function($step) {
                    return [
                        'stepNumber' => $step['step_number'],
                        'description' => $step['description'],
                        'image' => $step['image'],
                        'time' => $step['time']
                    ];
                }, $steps),
                'tips' => $recipe['tips'],
                'nutritionalValue' => $recipe['nutritional_value']
            ];
            
            return apiSuccess($recipeDetail);
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
    
    /**
     * 创建定制食谱
     */
    public function createCustomRecipe($data) {
        try {
            $userId = $this->getUserIdFromToken($data['token']);
            validateParams($data, ['name', 'ingredients', 'steps', 'date']);
            
            // 计算营养信息
            $nutritionInfo = $this->calculateNutrition($data['ingredients']);
            
            // 保存定制食谱
            $stmt = $this->db->prepare("INSERT INTO user_recipes (user_id, name, ingredients, steps, calories, protein, carbohydrate, fat, sugar, purine, date, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $userId,
                $data['name'],
                json_encode($data['ingredients']),
                json_encode($data['steps']),
                $nutritionInfo['calories'],
                $nutritionInfo['protein'],
                $nutritionInfo['carbohydrate'],
                $nutritionInfo['fat'],
                $nutritionInfo['sugar'],
                $nutritionInfo['purine'],
                $data['date']
            ]);
            
            $recipeId = $this->db->lastInsertId();
            
            return apiSuccess(['recipeId' => $recipeId], '定制食谱创建成功');
            
        } catch (Exception $e) {
            return apiError($e->getMessage());
        }
    }
    
    /**
     * 生成推荐食谱
     */
    private function generateRecommendations($healthInfo) {
        $conditions = [];
        
        // 根据血糖水平判断
        if ($healthInfo['blood_sugar'] > 7.0) {
            $conditions[] = 'diabetes';
        }
        
        // 根据尿酸水平判断
        if ($healthInfo['uric_acid'] > 420) {
            $conditions[] = 'gout';
        }
        
        // 根据BMI判断
        if ($healthInfo['bmi'] > 24) {
            $conditions[] = 'weight_control';
        }
        
        $sql = "SELECT * FROM recipes WHERE status = 1";
        $params = [];
        
        if (!empty($conditions)) {
            $sql .= " AND (";
            $conditionsSql = [];
            foreach ($conditions as $condition) {
                $conditionsSql[] = "JSON_CONTAINS(suitable_for, ?)";
                $params[] = json_encode([$condition]);
            }
            $sql .= implode(' OR ', $conditionsSql) . ")";
        }
        
        $sql .= " ORDER BY RAND() LIMIT 6";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        $recipes = $stmt->fetchAll();
        
        return array_map([$this, 'formatRecipe'], $recipes);
    }
    
    /**
     * 生成每日推荐
     */
    private function generateDailyRecommendations($healthInfo, $date) {
        return [
            'date' => $date,
            'breakfast' => $this->getMealRecommendation('breakfast', $healthInfo),
            'lunch' => $this->getMealRecommendation('lunch', $healthInfo),
            'dinner' => $this->getMealRecommendation('dinner', $healthInfo),
            'snack' => $this->getMealRecommendation('snack', $healthInfo)
        ];
    }
    
    /**
     * 获取用户健康信息
     */
    private function getUserHealthInfo($userId) {
        $stmt = $this->db->prepare("SELECT * FROM user_health WHERE user_id = ?");
        $stmt->execute([$userId]);
        return $stmt->fetch() ?: [];
    }
    
    /**
     * 格式化食谱
     */
    private function formatRecipe($recipe) {
        return [
            'id' => $recipe['id'],
            'name' => $recipe['name'],
            'image' => $recipe['image'],
            'description' => $recipe['description'],
            'calories' => $recipe['calories'],
            'cookingTime' => $recipe['cooking_time'],
            'difficulty' => $recipe['difficulty'],
            'tags' => json_decode($recipe['suitable_for'], true) ?: []
        ];
    }
    
    /**
     * 计算营养信息
     */
    private function calculateNutrition($ingredients) {
        // 简化计算，实际需要根据食材数据库计算
        return [
            'calories' => 0,
            'protein' => 0,
            'carbohydrate' => 0,
            'fat' => 0,
            'sugar' => 0,
            'purine' => 0
        ];
    }
    
    /**
     * 从token中获取用户ID
     */
    private function getUserIdFromToken($token) {
        // 简化实现，实际应该复用UserController中的方法
        $parts = explode('.', $token);
        if (count($parts) !== 3) {
            throw new Exception('Token格式错误');
        }
        
        $payload = json_decode(base64_decode($parts[1]), true);
        return $payload['user_id'];
    }
}

?>